import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.concurrent.atomic.AtomicBoolean;


public class CanvasGame extends Canvas implements Game, Runnable {
	private static final long serialVersionUID = 1L;
	private Thread gameThread;
    private AtomicBoolean running;
    private Input input;
    private MainScene scene;
    private long save_time;
    private InputToo inputToo;
    public CanvasGame(Dimension screenSize) {
        running = new AtomicBoolean(false);
        setSize(screenSize);
        initInput();
        initFocusListener();
    	Input.cursor_std = Toolkit.getDefaultToolkit().createImage(getClass().getResource("cursor_std.png"));
    	Input.cursor = Toolkit.getDefaultToolkit().createImage(getClass().getResource("chip.png"));
    	DesktopGameBuilder.frame.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(Input.cursor_std, new Point(8,8), "CustomCursor1"));
    }
    private void initInput() {
        input = new Input();
        addMouseListener(input);
        inputToo = new InputToo();
        addKeyListener( inputToo );
    }
    private void initFocusListener() {
        addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent event) {
                start();
            }
            @Override
            public void focusLost(FocusEvent event) {
                pause();
            }
        });
    }
    @Override
    public void start() {
        if (running.compareAndSet(false, true)) 
        {
            gameThread = new Thread(this);
            gameThread.start();
            MainScene.start = java.lang.System.currentTimeMillis() - save_time;
        }
    }
    @Override
    public void pause() {
    	save_time = java.lang.System.currentTimeMillis()-MainScene.start;
        if (running.compareAndSet(true, false)) {
            try {
                gameThread.join();
            } catch (InterruptedException exception) {
                throw new RuntimeException(exception);
            }
        }
    }
    @Override
    public Dimension getScreenSize() {
        return getSize();
    }
    @Override
    public Input getInput() {
        return input;
    }
    @Override
    public void setScene(MainScene scene) {
        this.scene = scene;
    }
    @Override
    public void run() {
        long previousIterationTime = System.nanoTime();
        while (running.get()) {
            if (scene == null) {
                continue;
            }
            long now = System.nanoTime();
            long nanosPassed = now - previousIterationTime;
            previousIterationTime = now;
            Graphics2D g = (Graphics2D)getBufferStrategy().getDrawGraphics();
           
            scene.update(nanosPassed);
            scene.draw(g);
            getBufferStrategy().show();
        }
    }
}